package com.cep.client;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.widget.TextView;

public class UDPSender {
	private static UDPSender instance = null;

	public static void init(TextView consoleOutputTV_) {
		instance = new UDPSender(consoleOutputTV_);
	}

	public static UDPSender instance() {
		return instance;
	}

	private TextView consoleOutputTV = null;
	private String ownIP = null;

	private UDPSender(TextView consoleOutputTV_) {
		this.consoleOutputTV = consoleOutputTV_;
	}

	public boolean sendUDPMessage(byte[] byteArray) {
		try {
			InetAddress serverAddr = InetAddress.getByName(ServerIPWatcher
					.instance().getServerIP());
			DatagramSocket socket = new DatagramSocket();
			DatagramPacket packet = new DatagramPacket(byteArray,
					byteArray.length, serverAddr, ServerPortWatcher.instance()
							.getServerPortInteger());
			socket.send(packet);
			return true;
		} catch (Exception e) {
			consoleOutputTV.setText(e.toString());
			return false;
		}
	}

	public String getLocalIpAddress() {
		if (ownIP != null)
			return ownIP;
		else {
			try {
				for (Enumeration<NetworkInterface> en = NetworkInterface
						.getNetworkInterfaces(); en.hasMoreElements();) {
					NetworkInterface intf = en.nextElement();
					for (Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							return (ownIP = inetAddress.getHostAddress()
									.toString());
						}
					}
				}
			} catch (SocketException ex) {
				consoleOutputTV.setText(ex.toString());
			}
			return null;
		}
	}
}
